package com.qgzj.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baidu.aip.ocr.AipOcr;
import com.google.common.collect.Maps;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @ClassName OcrService
 * @Description TODO
 * @DATE 2019-11-15 14:23
 **/
@Service
public class OcrService {
    //百度开发者中的新建实例的账号
    public static final String APP_ID = "17776607";
    public static final String API_KEY = "8YT4NF09IQLvdKTHiNrC7RfM";
    public static final String SECRET_KEY = "7ZUBroBqOHpgUYCxXZmYob0PrDMiaRGQ";
    private Logger logger = LoggerFactory.getLogger(OcrService.class);

    //获取百度OCR客户端
    public AipOcr getOcrClient() {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        return client;
    }

    //通用文字识别  50000次/天免费
    public String bdCommonOcr(AipOcr client, String picUrl) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
//        options.put("probability", "true");

       /* // 参数为本地路径
        String image = "test.jpg";
        JSONObject res = client.basicGeneral(image, options);
        System.out.println(res.toString(2));

        // 参数为二进制数组
        byte[] file = readFile("test.jpg");
        res = client.basicGeneral(file, options);
        System.out.println(res.toString(2));*/

        // 通用文字识别, 图片参数为远程url图片
        JSONObject res = client.basicGeneralUrl(picUrl, options);
        return res.toString();
    }

    public String processText(String json) {
        StringBuffer res = new StringBuffer();
        HashMap<String, String> map = Maps.newHashMap();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(json);
        boolean errorCode = jsonObject.containsKey("error_code");
        if (errorCode) {
            map.put("code", jsonObject.getString("error_code"));
            map.put("text", jsonObject.getString("error_msg"));
            return JSON.toJSONString(map);
        }
        if (jsonObject.containsKey("words_result")) {
            JSONArray array = jsonObject.getJSONArray("words_result");
            for (int i = 0; i < array.size(); i++) {
                com.alibaba.fastjson.JSONObject parse = JSON.parseObject(array.get(i).toString());
                String words = parse.getString("words");
                res.append(words);
                res.append(System.lineSeparator());
            }
            logger.info("识别的图片内容为" + "\r\n" + " {}", res);
            map.put("code", "0");
            map.put("text", res.toString());
            return JSON.toJSONString(map);
        }
        map.put("code", "-1");
        map.put("text", "未知错误");
        return JSON.toJSONString(map);
    }

}
